package com.ssyx.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ssyx.exception.SsyxException;
import com.ssyx.mapper.RegionMapper;
import com.ssyx.mapper.WareMapper;
import com.ssyx.model.sys.Region;
import com.ssyx.model.sys.RegionWare;
import com.ssyx.model.sys.Ware;
import com.ssyx.result.ResultCodeEnum;
import com.ssyx.service.WareService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @program: ssyx-parent
 * @className: WareServiceImpl
 * @description:
 * @data: 2024/3/9 16:52
 * @author: ihu
 * @version: 1.0
 **/

@Slf4j
@Service
public class WareServiceImpl extends ServiceImpl<WareMapper, Ware> implements WareService {
	
	@Resource
	private RegionMapper regionMapper;
	
	@Override
	public void saveWare(RegionWare regionWare) {
		String name = regionWare.getWareName();
		String city = regionWare.getRegionName();
		if (name == null || name.equals(" ") || name.isEmpty()) {
			log.error("新增仓库失败：仓库名不能为空");
			throw new SsyxException(ResultCodeEnum.ILLEGAL_PARAM);
		}
		if (city == null || city.equals(" ") || city.isEmpty()) {
			log.error("新增仓库失败：城市不能为空");
			throw new SsyxException(ResultCodeEnum.ILLEGAL_PARAM);
		}
		Region region = selectRegion(regionMapper.selectOne(Wrappers.<Region>lambdaQuery().eq(Region::getId,
				regionWare.getRegionId())));
		if (!city.contains("市") || !region.getName().contains("省")) {
			log.error("新增仓库失败：开通区域必须为市级");
			throw new SsyxException(ResultCodeEnum.REGION_CITY);
		}
		;
		Ware one = getOne(Wrappers.<Ware>lambdaQuery().eq(Ware::getName, name).or().eq(Ware::getCity, city));
		if (one != null) {
			log.error("新增仓库失败：仓库名称已存在或该城市已存在仓库");
			throw new SsyxException(ResultCodeEnum.INFORMATION_EXIST);
		}
		Ware ware = new Ware();
		ware.setName(name);
		ware.setProvince(String.valueOf(region.getParentId()));
		ware.setCity(city);
		ware.setDistrict(String.valueOf(regionWare.getRegionId()));
		if (!name.contains("仓库")) {
			name = regionWare.getWareName() + "仓库";
		}
		ware.setDetailAddress(region.getName() + "-" + city + "-" + name);
		save(ware);
	}
	
	private Region selectRegion(Region region) {
		if (region.getParentId().toString().length() > 2) {
			region = regionMapper.selectOne(Wrappers.<Region>lambdaQuery().eq(Region::getId,
					region.getParentId()));
			selectRegion(region);
		}
		return region;
	}
}
